pub fn convert_base(
  num_str: &str,
  to_base: u32,
) -> String {
  if to_base < 2 || to_base > 16 {
    return String::from("Invalid target base");
  }

  let parts: Vec<&str> = num_str.split('(').collect();
  if parts.len() != 2 || !parts[1].ends_with(')') {
    return String::from("Invalid input format");
  }

  let number_part = parts[0];
  let from_base_part = &parts[1][..parts[1].len() - 1]; // 去掉最后一个 ')'

  // 将输入进制转换为数字
  let from_base: u32 = match from_base_part.parse() {
    Ok(base) if base >= 2 && base <= 16 => base,
    _ => return String::from("Invalid input base"),
  };

  // 将输入的数字从 `from_base` 转换为 10 进制
  let decimal_value = match u32::from_str_radix(number_part, from_base) {
    Ok(value) => value,
    Err(_) => return String::from("Invalid number for the given base"),
  };

  // 将 10 进制数字转换为目标进制
  let result = match to_base {
    2 => format!("{:b}", decimal_value),
    8 => format!("{:o}", decimal_value),
    10 => format!("{}", decimal_value),
    16 => format!("{:x}", decimal_value),
    _ => convert_to_base(decimal_value, to_base),
  };

  result
}

fn convert_to_base(
  mut value: u32,
  base: u32,
) -> String {
  let mut result = String::new();
  let digits = "0123456789ABCDEF";

  while value > 0 {
    let digit = value % base;
    result.insert(0, digits.chars().nth(digit as usize).unwrap());
    value /= base;
  }

  if result.is_empty() {
    result.push('0');
  }

  result
}
